package com.example.es.service;

import com.example.es.dao.UserInfoRepository;
import com.example.es.dao.VideoRepository;
import com.example.es.vo.UserInfo;
import com.example.es.vo.Video;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ProjectName es
 *
 * @author xieyucan
 * <br>CreateDate 2022/12/29 10:25
 */
@Service
public class ElasticSearchService {

    @Resource
    private UserInfoRepository userInfoRepository;

    @Resource
    private VideoRepository videoRepository;

    @Resource
    private RestHighLevelClient restHighLevelClient;

    public void addUserInfo(UserInfo userInfo){
        userInfoRepository.save(userInfo);
    }

    public void addVideo(Video video){
        videoRepository.save(video);
    }

    public Video getVideos(String keyword){
        return videoRepository.findByTitleLike(keyword);
    }

    public List<Map<String,Object>> getContents(String keyword,
                                                Integer pageNo,
                                                Integer pageSize) throws IOException {
        String []indices={"user-infos","videos"};
        SearchRequest searchRequest = new SearchRequest(indices);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(pageNo-1);
        sourceBuilder.size(pageSize);

        MultiMatchQueryBuilder multiMatchQuery
                = QueryBuilders.multiMatchQuery(keyword, "title", "nick", "description");
        sourceBuilder.query(multiMatchQuery);
        searchRequest.source(sourceBuilder);

        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //高亮显示
        String[] array = {"title", "nick", "description"};
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        for(String key:array){
            highlightBuilder.fields().add(new HighlightBuilder.Field(key));
        }
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style=\"color=red\">");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
        //开始搜索
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String,Object>> arrayList=new ArrayList<>();
        SearchHits hits = searchResponse.getHits();
        for(SearchHit hit:hits){
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            for(String key:array){
                HighlightField highlightField = highlightFields.get(key);
                if(highlightField!=null){
                    Text[] fragments = highlightField.getFragments();
                    String str = Arrays.toString(fragments);
                    str=str.substring(1,str.length()-1);
                    sourceAsMap.put(key,str);
                }
            }
            arrayList.add(sourceAsMap);
        }
        return arrayList;
    }


}
